﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using App.Core.Extensions;
using App.Data;


public partial class Pages_Admin_SendNewsletter : BasePage
{
    protected int _NewsLetterID = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindDropdownLists();
        }
    }

    protected void BindPageInfo()
    {
        Page.Title = WebUtil.GetPageTitle("Send Newsletter");
    }

    protected void BindDropdownLists()
    {
        BindDropdownList.Newsletters(ddlTitle);
    }

    protected void ddlTitle_SelectedIndexChanged(object sender, EventArgs e)
    {
        _NewsLetterID = ddlTitle.SelectedValue.ToInt();
        BtcHousingEntities context = new BtcHousingEntities();
        NewsLetter newsLetter = context.NewsLetters.FirstOrDefault(P => P.ID == _NewsLetterID);
        if (newsLetter == null)
            divNewsletterHtml.InnerHtml = String.Empty;
        else
            divNewsletterHtml.InnerHtml = newsLetter.Html;
    }
    [WebMethod]
    public static String SendNewsLetters(int newsLetterID, String subject, String recipients)
    {
        String [] parts = recipients.Split(',');
        IList<int> userGroupIDs = new List<int>();
        foreach (String part in parts)
            userGroupIDs.Add(part.ToInt());

        int totalEmailSent = 0;
        BtcHousingEntities context = new BtcHousingEntities();
        var newsLetter = context.NewsLetters.FirstOrDefault(P => P.ID == newsLetterID);
        if (userGroupIDs.Count > 0 && newsLetter != null)
        {            
            foreach (int groupID in userGroupIDs)
            {
                if (groupID == ConfigReader.DeveloperUserGroupID)
                {
                    totalEmailSent = sendEmailToCompanies(newsLetter, subject, false);
                }
                else if (groupID == ConfigReader.ServiceProviderUserGroupID)
                {
                    totalEmailSent += sendEmailToCompanies(newsLetter, subject, true);
                }
                else if (groupID == ConfigReader.IndividualUserGroupID)
                {
                    totalEmailSent += sendEmailToIndividuals(newsLetter, subject);
                }
                else if (groupID == 0) ///News Letter Subscribers
                {
                    totalEmailSent += sendEmailToNewsletterSubscribers(newsLetter, subject);
                }
            }
        }
        return String.Format("Newsletter Sent to {0} recipients.", totalEmailSent);
    }

    private static int sendEmailToCompanies(NewsLetter newsLetter, string subject, bool isServiceProvider)
    {
        BtcHousingEntities context =  new BtcHousingEntities();
        int totalCount = 0;
        //var query = from P in context.Customers where P.BusinessTypeID == ConfigReader.DeveloperBusinessTypeID select P;
        IQueryable<Customer> query = null;
        if(isServiceProvider)
            query = from P in context.Customers 
                    where ConfigReader.ServiceProviderBusinessTypeIDs.Contains(P.BusinessTypeID) 
                        && !P.IsDeleted && P.IsApproved
                    select P;
        else
            query = from P in context.Customers where P.BusinessTypeID == ConfigReader.DeveloperBusinessTypeID
                        && !P.IsDeleted && P.IsApproved
                    select P;

        if (query != null && query.Count() > 0)
        {
            IList<Customer> developers = query.ToList();
            foreach (Customer developer in developers)
            {
                ///Send Emails to Company Email First
                var address = developer.Addresses.Count > 0 ? developer.Addresses.FirstOrDefault() :  null;               
                if (address != null && !address.Email.IsNullOrEmpty())
                {
                    WebUtil.SendMail(ConfigReader.SupportEmail, address.Email, String.Empty, String.Empty, subject, newsLetter.Html);
                    totalCount++;
                }
                ///Send Email Contacts
                var contactsQuery = from P in context.Contacts
                                    where P.CustomerID == developer.ID
                                        && !P.IsDeleted
                                    select P;

                foreach (Contact contact in contactsQuery)
                {
                    if (!contact.Email.IsNullOrEmpty())
                    {
                        WebUtil.SendMail(ConfigReader.SupportEmail, contact.Email, String.Empty, String.Empty, subject, newsLetter.Html);
                        totalCount++;
                    }
                }
            }
        }
        //System.Threading.Thread.Sleep(2000);
        return totalCount;
    }

    private static int sendEmailToIndividuals(NewsLetter newsLetter, string subject)
    {
        int totalCount = 0;
        BtcHousingEntities context = new BtcHousingEntities();
        var query = from P in context.Users
                    where P.GroupID == ConfigReader.IndividualUserGroupID
                        && P.IsActive && P.Customer.IsApproved && !P.IsDeleted & !P.Customer.IsDeleted
                    select P;
        if (query != null && query.Count() > 0)
        {
            IList<User> individuals = query.ToList();
            foreach (User individual in individuals)
            {
                WebUtil.SendMail(ConfigReader.SupportEmail, individual.LoginName, String.Empty, String.Empty, subject, newsLetter.Html);
                totalCount++;
            }
        }
        return totalCount;
    }
    private static int sendEmailToNewsletterSubscribers(NewsLetter newsLetter, string subject)
    {
        int totalCount = 0;
        BtcHousingEntities context = new BtcHousingEntities();
        var query = from P in context.NewsletterSubscribers where P.IsActive select P;                    
        foreach (NewsletterSubscriber subscriber in query)
        {
            WebUtil.SendMail(ConfigReader.SupportEmail, subscriber.Email, String.Empty, String.Empty, subject, newsLetter.Html);
            totalCount++;
        }        
        return totalCount;
    }
}